package com.weixin.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.weixin.bean.FoodType;
import com.weixin.service.FoodTypeService;
import com.weixin.service.impl.FoodTypeServiceimpl;

@WebServlet("/FoodTypeServlet/*")
public class FoodTypeServlet extends HttpServlet {

	/**
	 * 
	 */
	private FoodTypeService foodTypeService=new FoodTypeServiceimpl();
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String pathInfo = request.getPathInfo().substring(1);
		if (pathInfo.equals("listFoodType")) {
			listFoodType(request, response);
		}else if("removeByIdJson".equals(pathInfo)) {
			removeByIdJson(request,response);
		}else if("addFoodType".equals(pathInfo)) {
			addFoodType(request,response);
		}
	}

	private void addFoodType(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		FoodType foodType=new FoodType();
		foodType.setTypeName(request.getParameter("typeName"));
		Boolean b=foodTypeService.save(foodType);
		if(b) {
			response.getWriter().print(1);
		}else {
			response.getWriter().print(0);
		}
	}

	private void removeByIdJson(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		int id = Integer.valueOf(request.getParameter("id"));
		if(foodTypeService.delete(id)) {
			response.getWriter().print(1);
		}else {
			response.getWriter().print(0);
		}
	}

	private void listFoodType(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/javascript; charset=utf-8");
		List<FoodType> foodTypeList= foodTypeService.getAll();
		Map map = new HashMap();
		map.put("total", foodTypeList.size());
		map.put("rows", foodTypeList);
		Gson gson = new Gson();
		response.getWriter().print(gson.toJson(map));
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
